package secondary.vo;

import jade.content.Concept;
import jade.content.ContentElement;
import jade.content.lang.Codec;
import jade.content.lang.sl.SLCodec;
import jade.content.onto.Ontology;
import jade.content.onto.basic.Action;
import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;
import jade.util.leap.ArrayList;
import jade.util.leap.HashMap;
import jade.util.leap.Iterator;
import ontology.EmploymentLawOntology;
import ontology.VOOntology;
import ontology.actions.general.AddNewResult;
import ontology.actions.general.AddNewTime;
import ontology.concepts.general.Result;
import ontology.concepts.vo.VONewTime;
import ontology.concepts.vo.VOResult;
import classes.UMCourtAgent;
import ontology.UMCourtLVocabulary;
import utils.DBUtils;

public class EvaluatorVO extends UMCourtAgent 
{
	private Codec codec = new SLCodec();
	private Ontology ontology = VOOntology.getInstance();
	
	protected void setup() 
	{
		System.out.println(getDate()+ ": "+this.getLocalName()+" agent is now running...");
		registerAgent((String)getArguments()[0]);
		
		// Register language and ontology
	    getContentManager().registerLanguage(codec);
	    getContentManager().registerOntology(ontology);
		
		System.out.println(getDate()+" : Connected to Database");
		
		//printStats();
		
		this.addBehaviour(new receiveBehaviour());
	}
	
	class receiveBehaviour extends CyclicBehaviour
	{
		@Override
		public void action() 
		{
			ACLMessage msg = null;
			while((msg = blockingReceive())==null)
				;
	        
	        try 
			{
	        	ContentElement content = getContentManager().extractContent(msg);
		        Concept action = ((Action)content).getAction();
         		
		        switch (msg.getPerformative()) 
		        {
		        case (ACLMessage.REQUEST):
			        if (action instanceof AddNewResult)
			        {
			        	content = getContentManager().extractContent(msg);
			            AddNewResult nr = (AddNewResult) ((Action)content).getAction();
			            VOResult result = new VOResult();
			            result.setAgent(msg.getSender().getName());
			            result.setResult(nr.getNewResult());
			            DBUtils.saveOrUpdate(result);
			        }
		        	if (action instanceof AddNewTime)
		        	{
		        		content = getContentManager().extractContent(msg);
			            AddNewTime nt = (AddNewTime) ((Action)content).getAction();
			            VONewTime nvot = new VONewTime();
			            nvot.setConvId(msg.getConversationId());
			            nvot.setTime(nt.getTime());
			            nvot.setType(nt.getId());
			            DBUtils.saveOrUpdate(nvot);
			        }
		        }
			}
	        catch(Exception e){
	        	System.out.println("Algo correu mal no evaluator");
	        	e.printStackTrace();
	        	}
		}
	}
}
